<?php

namespace App\Controller\Admin;


use App\Helpers\Utils;
use App\Model\AdminHasPermission;
use App\Model\AdminPermission;
use App\Request\Admin\AdminLoginRequest;
use App\Controller\BaseController;
use App\Model\AdminUser;
use App\Service\Admin\AuthService;
use Carbon\Carbon;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\PostMapping;
use \Phper666\JwtAuth\Jwt;
use App\Middleware\RefreshTokenMiddleware;


/**
 * @AutoController()
 */
class AuthController extends BaseController
{
    public function login(AdminLoginRequest $request, Jwt $jwt)
    {
        $validated = $request->validated();

        $validated['password'] = Utils::password($validated['password']);

        $user = AdminUser::where($validated)->first();

        if (empty($user)){
            return $this->failed('账号或密码错误');
        }

        $userData = [
            'id'    => $user->id,
            'guard' => 'admin',
        ];

        $_server = $this->request->getServerParams();

        $user->update([
            'last_count'    =>  $user->last_count + 1,
            'last_at'       =>  Carbon::now()->toDateTimeString(),
            'last_ip'       =>  $_server['remote_addr']
        ]);

        $token = $jwt->getToken($userData);

        return $this->success(['token' => 'bearer ' . $token]);
    }


    /**
     * @PostMapping()
     * @Middleware(RefreshTokenMiddleware::class)
     */
    public function logOut()
    {
        var_dump($this->request->getAttribute('user'));
    }

    /**
     * @GetMapping()
     * @Middleware(RefreshTokenMiddleware::class)
     */
    public function info()
    {
        //  当前登陆用户
        $user = $this->attr();

        $hasMenus = AdminHasPermission::where('admin_id',$user->id)->pluck('permission_id');

        $menus = AdminPermission::whereIn('id',$hasMenus)->where('type',1)->pluck('path');
        $permissions = AdminPermission::whereIn('id',$hasMenus)->where('type',2)->pluck('remark');

        $user->roles = $menus;
        $user->permissions = $permissions;

        return $this->success($user);
    }

    /**
     * 获取用户菜单
     */
    public function menus()
    {
        $data = (new AuthService)->getMenus($this->request->getAttribute('user'));

        return $this->success($data);
    }
}
